import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

public class WordProcessor {

    public static void main(String[] args) {
        String filePath = "单词本.txt";
        String filePathWithFrequency = "单词本(带词频).txt";
        String filePathNotWithFrequency = "单词本(不带词频).txt";

        try {
           synchronized(filePath){
             Map<String,Integer> processedWords = processFile(filePath,true);
            writeFile(filePathWithFrequency, processedWords);
            }

            Map<String,Integer> processedWords2 = processFile(filePath,false);
            writeFile(filePathNotWithFrequency, processedWords2);

            System.out.println("文件处理完成！");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Map<String, Integer> processFile(String filePath,boolean isWithfFrequency) throws IOException {
        Map<String, Integer> processedWords = new HashMap<>();
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        String line;
        Pattern pattern = Pattern.compile("\\([^\\)]*\\)"); // 匹配括号及其内部内容

        while ((line = reader.readLine()) != null) {
            String[] parts = line.split("(?<=\\)\\s)");
            for (String word : parts) {
                word = word.trim();
                if(!isWithfFrequency){ word = pattern.matcher(word).replaceAll(""); // 移除匹配的括号及其内部内容
                }
                if (!word.isEmpty()) { 
                    processedWords.put(word,processedWords.getOrDefault(word, 0) + 1);
                }
            }
        }

        reader.close();
        return processedWords;
    }

    public static void writeFile(String filePath, Map<String, Integer> words) throws IOException {
        BufferedWriter writer = new BufferedWriter(new FileWriter(filePath));
        Integer flagCount = 0;
        List<Map.Entry<String, Integer>> lists = new ArrayList<>(words.entrySet());
        lists.sort(Map.Entry.<String, Integer>comparingByValue().reversed().thenComparing(Map.Entry.<String, Integer>comparingByKey()));
        for (Map.Entry<String, Integer> entry : lists) {
            flagCount += 1;
             String word = entry.getKey();
            int count = entry.getValue();
            writer.write(word);
            writer.newLine();
            if(flagCount>1 && (flagCount%101)==0){
                writer.newLine();
                writer.newLine();
            }
        }
        writer.close();
    }
}
